<template lang="pug">
.ignore-pacs-acquisition
  .ignore-pacs-acquisition-body
    .ignore-pacs-acquisition-body-top
      span 图像入库到
      Select(style="width: 130px;min-width: 130px;",:options="selectOptions" v-model="select")
      el-checkbox()
      span 采集声音
      mt-button(type="primary",@click="takePhoto",:loading="loadingMap['saveDcmImage'] || loadingMap['metadataUpload']") 采集(F8)
      mt-button(type="primary",:loading="loadingMap['saveDcmImage'] || loadingMap['metadataUpload']") 采集设置
      el-upload(
        class="avatar-uploader"
        :http-request="httpRequest"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        accept=".jpg, .jpeg, .png, .gif"
      )
        mt-button(type="primary",:loading="loadingMap['saveDcmImage'] || loadingMap['metadataUpload']") 导入图像
    .ignore-pacs-acquisition-body-center
      //-<!-- 播放器，用来播放拍摄的视频 -->
      video(class="camera_video" ref="videoDom",src="./lib/earth.mp4",:autoplay="true", :loop="true" muted) 
        //- dwv(:selectItemTag="props.selectItemTag",ref="RefDwv")
  .ignore-pacs-acquisition-imglist
    SectionTitle 已采图像
    .image__preview
      el-image(
        v-for="(url, index) in srcList"
        style="width: 100px; height: 100px"
        :src="url"
        :zoom-rate="1.2"
        :max-scale="7"
        :min-scale="0.2"
        :preview-src-list="srcList"
        :initial-index="4"
        fit="cover"
          @contextmenu.prevent="handleRightClick(index)"
      )
</template>
<script setup lang="ts">
import { SectionTitle, Select, useNotify, ElMessageBox } from "@scmt/common-components";
//@ts-ignore
import dwv from "../../pacsViewer/components/dwv.vue";
import { useRequest } from "@scmt/common-hooks";
import { useApi, type ApiBasedOptions } from "@scmt/core-api";
//@ts-ignore
import type { EntryTypeEntity, EntryTypeQueryParams } from "@scmt/api-pacs-entry-type";

import { useUtils } from "@scmt/lib-utils";

const $utils = useUtils();
//添加 Props属性
const props = defineProps({
  selectItemTag: Object,
});

//定义事件
const emit = defineEmits(["valueAdd", "imageChange"]);
const $api = useApi();
const { request, data, loadingMap } = useRequest({

  //根据类型查询术语
  entry: (typeId: string) => {
    return $api.pacs.entry.getEntryByTypeId(typeId);
  },
  //上传文件
  metadataUpload: (entity: any) => {
    return $api.fileUpload.metadataUpload(entity);
  },
  //保存dcm转为png 的png 数据
  saveDcmImage: async (entity: any) => {
    return await $api.pacs.imageData.save(entity);
  },
  //根据登记Id查询影像图片
  registrationImageData: async (registrationId: string) => {
    return await $api.pacs.imageData.queryByRegistrationId(registrationId);
  },
});

const $notify = useNotify();

const select = ref("1");
const selectOptions = reactive<ApiBasedOptions>([
  { label: "发送给此病人", value: "1" },
  { label: "发送给其他", value: "2" },
]);
const srcList = ref([
  'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',
]);

const imgurl = ref(null);
const videoDom = ref<HTMLVideoElement>();

const handleAvatarSuccess = (res: any, file: any) => {
  if (res && file) {
    let imageUrl = URL.createObjectURL(file.raw);
    srcList.value.push(imageUrl);
  }
};
const beforeAvatarUpload = (file: any) => {
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
  const isAllowed = allowedTypes.includes(file.type);
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isAllowed) {
    $notify.error('只能上传 JPG/PNG/GIF 格式的图片!');
  }
  if (!isLt5M) {
    $notify.error('上传头像图片大小不能超过 5MB!');
  }
  return isLt5M;
}
const httpRequest = (data: any) => {

  if (data && data.file) {
    const reader = new FileReader(); // 创建FileReader实例

    reader.onload = function (loadEvent: ProgressEvent) {
      //@ts-ignore
      const base64Data = loadEvent.target?.result;
      //console.log(base64Data);
      if (base64Data) {
        // 调用回调函数并传递Base64字符串
        handleBase64Data(base64Data, data.file.name);
      }

    };

    reader.onerror = function (error) {
      console.error('Error: ', error);
    };

    reader.readAsDataURL(data.file); // 读取文件并转换为Base64
  }
}
// 调用回调函数并传递Base64字符串
const handleBase64Data = (base64: string, fileName: string) => {
  if (base64 && fileName) {
    base64 = base64.split(',')[1]
  }
  const entity = $api.fileUpload.$$createEntity({ metadataName: fileName, metadataContent: base64 });
  //上传文件
  request("metadataUpload", entity).then(() => {
    const res = data.metadataUpload ?? null
    if (res && res.fileUrl) {
      srcList.value.push(res.fileUrl);
      //@ts-ignore
      imgurl.value = res.fileUrl;
      let item = $api.pacs.imageData.$$createEntity({ imageData: res.fileUrl, registrationId: props.selectItemTag?.id, updateTime: $utils.formatDate(new Date()) });
      request("saveDcmImage", item).then((res) => {
        if (res) {
          $notify.success("上传图片文件成功");
          emit("imageChange");
          openCamera();
        }
      });
    }
  })
};

//拍照
const openCamera = () => {
  //检测浏览器是否支持mediaDevices
  // if (navigator && navigator.mediaDevices) {
  //   navigator.mediaDevices
  //     // 开启视频，关闭音频
  //     .getUserMedia({ audio: false, video: true })
  //     .then((stream) => {
  //       // 将视频流传入viedo控件
  //       //@ts-ignore
  //       videoDom.value?.srcObject = stream;
  //       // 播放
  //       videoDom.value?.play();
  //     })
  //     .catch((err) => {
  //       console.log(err);
  //     });
  // } else {
  //   $notify.error("该浏览器不支持开启摄像头，请更换最新版浏览器");
  // }
  videoDom.value?.play();
};
const handleRightClick = (index: any) => {
  let registrationImageData = data.registrationImageData ?? [];
  if (index != null && registrationImageData.length > 0) {
    let item = $api.pacs.imageData.$$createEntity(registrationImageData[index] ?? {});
    if (item && item.id) {

      ElMessageBox.confirm("监测您右键了此图片，您是否确认将图片加入到报告里！", {
        title: "提示",
        type: "warning",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm" && instance) {
            // if (item.isReport == 1) {
            //   $notify.warning("当前图片已经在报告里面了！！");
            // }
            // else {
            Object.assign(item, { isReport: 1, updateTime: $utils.formatDate(new Date()) });
            request("saveDcmImage", item).then((res) => {
              if (res) {
                $notify.success("图片加入到报告里成功！！");
                emit("imageChange");
                openCamera();
              }
            });
            // }
            done();
          } else {
            done();
          }
        },
      });
    }
  }
}
// 拍照
const takePhoto = () => {
  // 如果已经拍照了就重新启动摄像头
  // if (imgurl.value) {
  //   imgurl.value = null;
  //   openCamera()
  //   return;
  // }
  if (videoDom.value) {

    // 创建一个canvas元素
    const canvas = document.createElement('canvas');
    // 设置画布大小与摄像大小一致
    canvas.width = videoDom.value.videoWidth;
    canvas.height = videoDom.value.videoHeight;
    // 执行画的操作
    //@ts-ignore
    canvas?.getContext("2d").drawImage(videoDom.value, 0, 0);
    // 将结果转换为可展示的格

    // 把生成的base64位图片上传到服务器,生成在线图片地址
    let url = canvas.toDataURL('image/png') // toDataURL: 图片格式转成 base64
    if (url) {
      // 调用回调函数并传递Base64字符串
      handleBase64Data(url, $utils.uuid() + "dcmurl.png");
    }


  }
};

watch(
  () => props.selectItemTag,
  (item) => {
    openCamera();
    if (item && item.id) {
      srcList.value = [];
      let registrationId = item.id;
      request("registrationImageData", registrationId).then(() => {
        let imageData = data.registrationImageData ?? [];
        if (imageData && imageData.length > 0) {
          let dcmUrl = ref<any>([]);
          imageData.forEach((element: any) => {
            if (element && element.imageData) {
              dcmUrl.value.push(element.imageData)
            }
          });
          srcList.value = dcmUrl.value;
        }

      });
    }
  },
  {
    immediate: true,
  }
);
</script>

<style lang="less" scoped>
.ignore-pacs-acquisition {
  padding-top: var(--mt-padding);
  height: 100%;
  display: flex;
  flex-direction: column;

  &-body {
    height: 60%;
    display: flex;
    flex-direction: column;

    &-top {
      display: flex;
      justify-items: center;
      align-items: center;
      flex-shrink: 0;
      margin-bottom: 4px;

      .el-checkbox {
        margin-left: var(--mt-margin-small);
      }

      span {
        display: flex;
        margin: 0 var(--mt-margin-small);
      }
    }


    &-center {
      flex: 1;
      border-radius: 0.208333vw;
      border: 1px solid var(--mt-card-border-color);
      background-color: black;
      height: calc(100% - 42px);

      .camera_video {
        height: 100%;
        width: 100%;
      }

      .canvas {
        display: none;
      }
    }

    .el-button {
      margin-left: 12px;
    }
  }

  &-imglist {
    height: 40%;
    border-radius: 0.208333vw;
    border: 1px solid var(--mt-card-border-color);
    margin-bottom: 8px;

    display: flex;
    flex-direction: column;

    .section-title {
      flex-shrink: 0;
      margin-top: var(--mt-margin);
      margin-bottom: var(--mt-margin);
    }

    .image__preview {
      flex: 1;
      background-color: black;
      padding-top: var(--mt-padding);
      overflow-y: auto;

      .el-image {
        margin-left: var(--mt-margin);
      }
    }
  }

  .section-title {
    padding-top: 0px !important;
    padding-bottom: 0px !important;
    font-size: 16px;
  }
}
</style>